/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

 /* METHOD
  * 
  */
 def checkRule = {
	 it, lista, listaWK ->
	 print "\n---- Regla ${it.@id}\n"
	 def valeRegla = true
	 def rule = new Rule()
	 rule.id = it.@id
	 it.if.attr.each{
		 if(valeRegla){
			 def nombre = it.@name
			 def valor = it.text()
			 def aBuscar = "" + nombre + "=" + valor
			 println "a buscar ${aBuscar}"

/* Comparo caracter por caracter */
			 def encontrado = false
			 listaWK.each {
				 def pos = 0
				 def sIgual = true
				 it.each {
					 if (it != aBuscar[pos])
						  sIgual = false
					 pos++
				 }
				 if (sIgual)
					  encontrado = true
			 }
			 if (encontrado)
			 rule.premises.put nombre, valor
			 else
			 valeRegla = false
/* */		 
			 /*if(!listaWK.contains(aBuscar)){
				 valeRegla = false
			 } else {
				 rule.premises.put(nombre, valor)
			 }*/
		 }
	 }
	 if(valeRegla){
		 println "   OK"
		 it.then.attr.each{
			 rule.conclusions.put(it.@name, it.text())
		 }
		 if(!lista.contains(rule)){
			 lista.add(rule)
		 }
		 else
		 println "  Esta regla ya esta en la WK"
	 }
	 else
	 println "   NO"
 }


/*
 * MAIN
 */

def records = new XmlParser().parse(new File("src/reglas.xml"));
/*
records.rule.each{
    println "\n==== Rule ${it.@id} ===="
    println "if"
    it.if.attr.each{
        println "   ${it.@name}  =  ${it.text()}"
    }
    println "then"
    it.then.attr.each{
        println "   ${it.@name}  =  ${it.text()}"
    }
}
*/

println "\n\n==== Motor de Inferencia ==> Para salir 'exit' ===="
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))

//print "Ingrese objetivo: "
def obj = "m=valorM"

//print "\nIngrese condiciones: "
//def input = br.readLine()
def entrada = "a=valorA,b=valorB,i=valorI,g=valorG,l=valorL"
def inputs = entrada.split(",")

def listaEntrada = new ArrayList<String>()
inputs.each{
    listaEntrada.add(it)
}

def workingMemory = new WorkingMemory()
def listRules = new ArrayList<Rule>()

workingMemory.memory = listaEntrada

def index = 0
def temp = entrada

while (!temp.contains(obj)){
	println ""
	println "###########"
	println "# BUCLE " + index
	println "###########"  
    records.rule.each{checkRule(it, listRules, workingMemory.memory)}

    //if(!listRules.isEmpty()){
	if (listRules[index] != null)
	{
		//println listRules
        workingMemory.addRule(listRules.get(index))
        //listRules.remove(index) //Es lo mismo borrarlo o dejarlo
    }
	else
	{
		break;
	}
    index++;
    temp = entrada + ","+workingMemory.getConclusions()
    println "" 
	workingMemory.printMemory()
}

if (temp.contains(obj))
{
	println "Se llego al objetivo"
}
else
{
	println "No se llego al objetivo"
}


